package com.wangdf;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

/**
 * Servlet
 * @author wangdf
 *
 */
public class Servlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String srcDir = "";
	private String resDir = "";
	
	public void service (HttpServletRequest req, HttpServletResponse resp)
			throws IOException  , ServletException
	{
		ServletContext s1=this.getServletContext(); 
		srcDir = s1.getRealPath("/") + "WEB-INF\\classes\\com\\ftl"; 
		resDir = req.getSession().getServletContext().getRealPath("/") ;
		testFreemarker();
		RequestDispatcher dispatcher = req.getRequestDispatcher("/new.html"); 
		dispatcher.forward(req, resp); 
	}
	

	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void testFreemarker(){
		try {
			Configuration cfg = new Configuration();
			
			//从什么地方加载freemarker模板文件
			cfg.setDirectoryForTemplateLoading(new File(srcDir));
			
			//设置对象包装器
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			
			//设置异常处理器
			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
			
			//定义Template对象
			Template template = cfg.getTemplate("map.ftl");
			
			//定义数据
			Map root = new HashMap();
			root.put("name", "王登峰");
			root.put("url", resDir + "copyright_footer.html");
			//天安门: 39.908288,116.398252
			root.put("longitude",116.398252);//经度
			root.put("latitude",39.908288);//纬度

			//定义输出
			PrintWriter out 
				= new PrintWriter(
					new BufferedWriter(
						new FileWriter(resDir+"\\new.html")
					)
				);
			
			//****最重要的就是这一步，动态加载 
			template.process(root, out);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
